package cn.kgc.service.impl;

import cn.kgc.entities.Emp;
import cn.kgc.mapper.EmpMapper;
import cn.kgc.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class EmpServiceImpl implements EmpService {
    @Autowired
    public RedisTemplate redisTemplate;

    @Resource
    private EmpMapper empMapper;
    @Override
    public void add(Emp emp) {

        empMapper.insert(emp);
    }

    @Override
    public Object getEmpById(Integer id) {
        String key = "user:" + id;
        Object user = redisTemplate.opsForValue().get(key);
        if (user == null) {
            synchronized (this.getClass()) {
                user = redisTemplate.opsForValue().get(key);
                if (user == null) {
                    log.debug("--------->查询数据库..........");
                    Emp emp = empMapper.selectByPrimaryKey(id);
                    redisTemplate.opsForValue().set(key, emp);
                    return emp;
                } else {
                    log.debug("------> 查询缓存（同步）>>>>>>>>>");
                    return user;
                }

            }

        } else {
            log.debug("--------->查询缓存..........");
        }
        return user;
    }
}
